// src/renderer/src/utils/session-manager.js
class SessionManager {
  constructor() {
    this.sessionCheckInterval = null;
    this.lastActivity = Date.now();
    this.setupActivityTracking();
  }

  // 设置用户活动跟踪
  setupActivityTracking() {
    // 监听用户活动
    const activities = ['mousemove', 'keypress', 'click', 'scroll'];
    activities.forEach(event => {
      document.addEventListener(event, () => {
        this.lastActivity = Date.now();
      });
    });

    // 定期检查会话状态
    this.sessionCheckInterval = setInterval(async () => {
      await this.checkSessionTimeout();
    }, 30000); // 每30秒检查一次
  }

  // 检查会话超时
  async checkSessionTimeout() {
    const inactiveTime = Date.now() - this.lastActivity;
    const fiveMinutes = 5 * 60 * 1000;

    if (inactiveTime > fiveMinutes) {
      // 会话超时，强制登出
      await this.forceLogout('会话超时，请重新登录');
    } else {
      // 验证会话是否有效
      try {
        const result = await window.electronAPI.invoke('auth-verify-session');
        if (!result.success && result.timeout) {
          await this.forceLogout(result.error);
        }
      } catch (error) {
        console.error('会话验证失败:', error);
      }
    }
  }

  // 强制登出
  async forceLogout(reason) {
    clearInterval(this.sessionCheckInterval);
    
    try {
      await window.electronAPI.invoke('auth-logout');
    } catch (error) {
      console.error('登出失败:', error);
    }

    // 跳转到登录页面
    if (window.vueRouter) {
      window.vueRouter.push('/login');
    }

    // 显示超时提示
    this.showTimeoutMessage(reason);
  }

  // 显示超时消息
  showTimeoutMessage(reason) {
    const message = document.createElement('div');
    message.style.cssText = `
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      background: #e74c3c;
      color: white;
      padding: 15px 20px;
      border-radius: 5px;
      z-index: 10000;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    `;
    message.textContent = reason;
    document.body.appendChild(message);

    setTimeout(() => {
      document.body.removeChild(message);
    }, 5000);
  }

  // 清理资源
  destroy() {
    if (this.sessionCheckInterval) {
      clearInterval(this.sessionCheckInterval);
    }
  }
}

export default new SessionManager();